package com.yunianvh.mobilecashierweb;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import java.util.ArrayList;
import java.util.List;

public class NeNotificationService extends NotificationListenerService {
    private String TAG = "NeNotificationService";
    private PowerManager.WakeLock mWakeLock = null;
    public static final String PAYMENT_RECEIVED_ACTION = "com.yunianvh.mobilecashierweb.PAYMENT_RECEIVED";
    public static final String EXTRA_PAYMENT_AMOUNT = "payment_amount";
    public static final String EXTRA_PAYMENT_PLATFORM = "payment_platform";

    //申请设备电源锁
    @SuppressLint("InvalidWakeLockTag")
    public void acquireWakeLock(Context context) {
        if (null == mWakeLock) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "WakeLock");
            if (null != mWakeLock) {
                mWakeLock.acquire();
            }
        }
    }

    //释放设备电源锁
    public void releaseWakeLock() {
        if (null != mWakeLock) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    //当收到一条消息的时候回调，sbn是收到的消息
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Log.d(TAG, "接受到通知消息");
        Notification notification = sbn.getNotification();
        String pkg = sbn.getPackageName();
        if (notification != null) {
            Bundle extras = notification.extras;
            if (extras != null) {
                String title = extras.getString(NotificationCompat.EXTRA_TITLE, "");
                String content = extras.getString(NotificationCompat.EXTRA_TEXT, "");
                Log.d(TAG, "**********************");
                Log.d(TAG, "包名:" + pkg);
                Log.d(TAG, "标题:" + title);
                Log.d(TAG, "内容:" + content);
                Log.d(TAG, "**********************");

                //新增：监听支付宝
                if (pkg.equals("com.eg.android.AlipayGphone")) {
                    if (content != null && !content.equals("")) {
                        if (content.indexOf("通过扫码向你付款") != -1 || content.indexOf("成功收款") != -1) {
                            String money = getMoney(content);
                            if (money != null) {
                                Log.d(TAG, "onAccessibilityEvent: 匹配成功： 支付宝 到账 " + money);
                                // 发送广播通知支付成功
                                sendPaymentReceivedBroadcast(money, "alipay");
                            } else {
                                Handler handlerThree = new Handler(Looper.getMainLooper());
                                handlerThree.post(() -> Toast.makeText(getApplicationContext(), "监听到支付宝消息但未匹配到金额！", Toast.LENGTH_SHORT).show());
                            }
                        }

                    }
                }
                //新增：监听微信
                else if (pkg.equals("com.tencent.mm")) {

                    if (content != null && !content.equals("")) {
                        if (title.equals("微信支付") || title.equals("微信收款助手") || title.equals("微信收款商业版")) {
                            String money = getMoney(content);
                            if (money != null) {
                                Log.d(TAG, "onAccessibilityEvent: 匹配成功： 微信到账 " + money);
                                // 发送广播通知支付成功
                                sendPaymentReceivedBroadcast(money, "wechat");
                            } else {
                                Handler handlerThree = new Handler(Looper.getMainLooper());
                                handlerThree.post(() -> Toast.makeText(getApplicationContext(), "监听到微信消息但未匹配到金额！", Toast.LENGTH_SHORT).show());
                            }

                        }
                    }

                }
                // 新增：监听云闪付 (UnionPay)
                else if (pkg.equals("cn.com.unionpay")) {
                    if (content != null && !content.isEmpty()) {
                        if (content.contains("向你付款") || content.contains("收款") || content.contains("支付成功")) {
                            String money = getMoney(content);
                            if (money != null) {
                                Log.d(TAG, "onAccessibilityEvent: 匹配成功： 云闪付 到账 " + money);
                                sendPaymentReceivedBroadcast(money, "unionpay");
                            } else {
                                Handler handlerThree = new Handler(Looper.getMainLooper());
                                handlerThree.post(() -> Toast.makeText(getApplicationContext(), "监听到云闪付消息但未匹配到金额！", Toast.LENGTH_SHORT).show());
                            }
                        }
                    }
                }
            }
        }
    }

    //当移除一条消息的时候回调，sbn是被移除的消息
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {

    }

    //当连接成功时调用，一般在开启监听后会回调一次该方法
    @Override
    public void onListenerConnected() {
        Handler handlerThree = new Handler(Looper.getMainLooper());
        handlerThree.post(() -> Toast.makeText(getApplicationContext(), "监听服务开启成功！", Toast.LENGTH_SHORT).show());
    }

    /**
     * 从通知内容中提取金额。
     * 改进：优先匹配包含“元”、“¥”或出现在“收款”、“到账”等关键词之后的数字。
     */
    public static String getMoney(String content) {
        // 首先尝试匹配 "收款 ¥X.XX" 或 "到账 X.XX元" 这类模式
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("(?:收款|到账|付款)[\\s：:]*[¥￥]?(\\d+(?:\\.\\d+)?)|(?:收款|到账|付款)[\\s：:]*(\\d+(?:\\.\\d+)?)[\\s]*(?:元|块钱)");
        java.util.regex.Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            // 返回第一个捕获组（¥后面的数字）或第二个捕获组（元前面的数字）
            return matcher.group(1) != null ? matcher.group(1) : matcher.group(2);
        }

        // 如果正则未匹配，则使用原有方法，取最后一个数字（通常是金额）
        List<String> numbers = new ArrayList<>();
        for (String numStr : content.replaceAll("[^0-9.]", ",").split(",")) {
            if (!numStr.isEmpty() && numStr.matches("\\d+(\\.\\d+)?")) {
                numbers.add(numStr);
            }
        }
        return numbers.isEmpty() ? null : numbers.get(numbers.size() - 1);
    }

    // 发送支付成功的广播
    private void sendPaymentReceivedBroadcast(String amount, String platform) {
        Log.d(TAG, "sendPaymentReceivedBroadcast 发送支付成功广播 价格：" + amount + " 平台：" + platform);
        Intent intent = new Intent(PAYMENT_RECEIVED_ACTION);
        intent.setPackage(getPackageName()); // 限制广播只能被本应用接收
        intent.putExtra(EXTRA_PAYMENT_AMOUNT, amount);
        intent.putExtra(EXTRA_PAYMENT_PLATFORM, platform);
        sendBroadcast(intent);
    }

}